/*
 * Copyright (c) 2014 - 2017. Company.Domain Co.Ltd. All rights reserved.
 */

package cn.com.dhc.danlu.activity.myself;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import cn.com.dhc.danlu.R;
import cn.com.dhc.danlu.activity.BaseActivity;
import cn.com.dhc.danlu.activity.RegisterActivity;
import cn.com.dhc.danlu.dlware.OperatorUtils;
import cn.com.dhc.danlu.dlware.net.GeneralBusinessObserver;
import cn.com.dhc.danlu.util.ToastUtil;
import cn.com.hd.mall.web.webservices.entity.request.regist.GetAreaRequest;
import cn.com.hd.mall.web.webservices.entity.response.regist.AreaResponse;
import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;

import static cn.com.dhc.danlu.dlware.global.DanluApplication.agent;

/**
 * author: 刘立琦(<a href="mailto:liuliqi@danlu.com">liuliqi@danlu.com</a>)<br/>
 * version: 1.0.0<br/>
 * since: 2017-01-16 11:32<br/>
 *
 * <p>
 * 收货地址管理——添加收货地址--所在区域---获得区域列表页面
 * </p>
 */
public class AddressListActivity extends BaseActivity implements OnClickListener {
    /**
     * 获取区域列表 请求
     */
    GetAreaRequest form;
    /**
     * 接收返回数据
     */
    AreaResponse areaListResponse;
    /**
     * 所选区域 名称
     */
    StringBuffer str;
    /**
     * 丹露用异步任务代理
     */
    // private DanluTaskProxy danluTaskProxy;
    /**
     * 画面Title
     */
    private TextView tvTitle;
    /**
     * 当前所选区域 文本框
     */
    private TextView tvGetSelectAdd;
    /**
     * LayoutInflater
     */
    private LayoutInflater layoutInflater;
    /**
     * 省份Code
     */
    private String provinceCode;
    /**
     * 城市Code
     */
    private String cityCode;
    /**
     * 区域列表容器
     */
    private LinearLayout llytAddressContainer;
    /**
     * 当前所选区域 LinearLayout
     */
    private LinearLayout llGetSelectAdd;
    /**
     * 区域UI元素List
     */
    private List<AddressHolder> addressHolders;
    /**
     * 下拉刷新容器
     */
    private PtrClassicFrameLayout ptrdd;
    private Intent intent;

    private boolean flag = false;

    public AddressListActivity() {
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 实例化画面控件
//        getDelegate ().setContentView (R.layout.layout_my_area_address, R.my_area.class);
        setContentView(R.layout.activity_address_list);

        initView();
        setViews();
    }

    private void initView() {
        llytBack = (LinearLayout) findViewById(R.id.llytBack);
        tvTitle = (TextView) findViewById(R.id.tv_title);
        llGetSelectAdd = (LinearLayout) findViewById(R.id.ll_get_select_add);
        tvGetSelectAdd = (TextView) findViewById(R.id.tv_get_select_address);
        ptrdd = (PtrClassicFrameLayout) findViewById(R.id.ptrdd);
        llytAddressContainer = (LinearLayout) findViewById(R.id.llytAddressContainer);
    }


    @Override
    protected String getActivityTitle() {
        return null;
    }

    /**
     * 页面初始化
     */
    private void setViews() {
        intent = new Intent();
        // 初始化LayoutInflater
        layoutInflater = LayoutInflater.from(this);
        tvTitle.setText(R.string.selete_province_title);
        form = new GetAreaRequest();
        // 设置参数,"CHN"返回省份列表
        form.setSearch("CHN");
        // 获取区域列表
        getAreaList();
        str = new StringBuffer();
        llytBack.setOnClickListener(this);
        ptrdd.setPtrHandler(new PtrHandler() {
            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return false;
            }

            @Override
            public void onRefreshBegin(final PtrFrameLayout frame) {
                frame.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        frame.refreshComplete();
                    }
                }, 2000);
            }
        });
    }

    /**
     * 获取地域列表
     */
    private void getAreaList() {
        agent.getApi().getAreaList(form).compose(OperatorUtils.<AreaResponse> defaultSchedulers())
                .subscribe(new GeneralBusinessObserver<AreaResponse>() {
                    @Override
                    protected void onSuccess(AreaResponse areaResponse) {
                        areaListResponse = areaResponse;
                        buildReceiveAddList(areaListResponse);
                    }

                    @Override
                    protected void onAlertTips(String displayMessage) {
                        ToastUtil.getInstance().show(TextUtils.isEmpty(displayMessage) ? "地域列表获取失败！" : displayMessage);
                    }
                });
    }

    /**
     * 构建区域列表
     */
    private void buildReceiveAddList(AreaResponse response) {
        flag = true;
        llytAddressContainer.removeAllViews();
        llytAddressContainer.removeAllViewsInLayout();

        if (addressHolders == null) {
            addressHolders = new ArrayList<>();
        } else {
            addressHolders.clear();
        }

        int modeSize = response.getAreaList().size();
        for (int i = 0; i < modeSize; i++) {
            View convertStoreView = layoutInflater.inflate(R.layout.view_area_address_item, null);
            AddressHolder itemHolder = findStoreItemView(convertStoreView);
            itemHolder.tvReceiveAddress.setText(response.getAreaList().get(i).getAreaName());
            addressHolders.add(itemHolder);
            itemHolder.tvReceiveAddress.setTag(i);
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            llytAddressContainer.addView(convertStoreView, lp);
            itemHolder.tvReceiveAddress.setOnClickListener(this);
        }
    }

    /**
     * get AddressHolder by spec view container
     */
    private AddressHolder findStoreItemView(View convertView) {
        AddressHolder holder = new AddressHolder();
        holder.tvReceiveAddress = (TextView) convertView.findViewById(R.id.tv_receive_address);

        return holder;
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.tv_receive_address) {
            if (flag) {
                flag = false;
                if (llGetSelectAdd.getVisibility() == View.GONE) { // 显示当前选择区域名称
                    llGetSelectAdd.setVisibility(View.VISIBLE);
                }
                int index = (Integer) v.getTag();
                if (provinceCode == null && cityCode == null) {
                    str.append(areaListResponse.getAreaList().get(index).getAreaName());
                    tvGetSelectAdd.setText(str.toString());
                    tvTitle.setText(R.string.selete_city_title);
                    provinceCode = areaListResponse.getAreaList().get(index).getAreaCode();
                    form.setSearch(provinceCode);
                    getAreaList();
                } else if (provinceCode != null && cityCode == null) {
                    str.append(areaListResponse.getAreaList().get(index).getAreaName());
                    tvGetSelectAdd.setText(str.toString());
                    tvTitle.setText(R.string.selete_district_title);
                    cityCode = areaListResponse.getAreaList().get(index).getAreaCode();
                    form.setSearch(cityCode);
                    getAreaList();
                } else if (provinceCode != null) {
                    str.append(areaListResponse.getAreaList().get(index).getAreaName());
                    tvGetSelectAdd.setText(str.toString());
                    // 区域Code
                    String districtCode = areaListResponse.getAreaList().get(index).getAreaCode();

                    if (getIntent() != null && getIntent().getStringExtra("REGISTER") != null) {
                        if (getIntent().getStringExtra("REGISTER").equals("register")) {
                            intent.setClass(AddressListActivity.this, RegisterActivity.class);
                        }
                    } else if (getIntent() != null && getIntent().getStringExtra("VAT") != null) {
                        if (getIntent().getStringExtra("VAT").equals("vatInvoice")) {
                            intent.setClass(AddressListActivity.this, MyInvoiceActivity.class);
                        }
                    } else {
                        intent.setClass(AddressListActivity.this, MyReceiveAddressActivity.class);
                    }
                    intent.putExtra("ADDR", str.toString());
                    intent.putExtra("PCODE", provinceCode);
                    intent.putExtra("CCODE", cityCode);
                    intent.putExtra("DCODE", districtCode);
                    AddressListActivity.this.setResult(100, intent);
                    finish();
                }
            }
        }

        switch (v.getId()) {
            case R.id.llytBack:
                finish();
                break;

            default:
                break;
        }
    }

    /**
     * 区域列表Holder
     */
    private static class AddressHolder {
        private TextView tvReceiveAddress;
    }
}